package cn.e3.cart.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.e3.pojo.TbUser;
import cn.e3.sso.service.TokenService;
import cn.e3.utils.CookieUtils;
import cn.e3.utils.E3Result;
@Controller
public class HandlerInterceptorController implements HandlerInterceptor{
	@Autowired
	private TokenService tokenService;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//执行handler之前的处理
		//从cookie中获得token
		String token = CookieUtils.getCookieValue(request, "token");
		//判断token是否存在，不存在直接放行
		if(StringUtils.isBlank(token)){
			return true;
		}
		//token 存在，在redis中获得用户信息，看是否过期
		E3Result e3Result = tokenService.getUserByToken(token);
		//判断用户是否过期
		if(e3Result.getStatus()!=200){
			return true;
		}
		//没过期，获取用户信息
		TbUser user=(TbUser) e3Result.getData();
		//将用户信息放入request域中
		request.setAttribute("user", user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// 执行handler之后，返回modelandview之前的处理
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 返回modelandvie之后的处理
		
	}

}
